import React, {useEffect, useRef, useState} from 'react';
import ReactQuill, {Quill} from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import 'quill-resize-module/dist/resize.css';
import ImageResize from 'quill-image-resize-module-react';
import classes from './index.module.scss'
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import {
    Button, Divider, Image, Popover, Space, message, Form, Input, Select, Upload, Tag, Modal,
} from "antd";
import icon from '../../../../assets/logo192.png'
import axios from "axios";
import {reqInsertDraft, reqPublishArticle} from "../../../../api/frontDesk/frontDeskApi";
import {useSelector} from "react-redux";
import {reqGetArticleSort} from "../../../../api/backStage/backStageApi";
import {useNavigate} from "react-router-dom";

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};


// 富文本编辑器的自定义工具栏
Quill.register('modules/imageResize', ImageResize);
const modules = {
    // 方式1: 可以是简单的一维数组配置
    // toolbar: ["bold", "italic", "underline", "strike", "blockquote"]
    // 方式2: 可以配置二维数组，进行多个选项的配置
    // 或者针对某一个配置项的key值，进行配置
    toolbar: [
        'bold', 'italic', 'underline',
        {header: 1}, {header: 2},
        'blockquote', 'link',
        {list: 'ordered'}, {list: 'bullet'},
        'image',
    ],
    imageResize: {
        parchment: Quill.import('parchment')
    }
    // 方式3: 可以自己指定工具栏的容器
}
const formats = [
    'header', 'font', 'size',
    'bold', 'italic', 'underline', 'strike', 'blockquote',
    'list', 'bullet', 'indent',
    'link', 'image', 'video'
]


const WriteArticle = () => {
    const {TextArea} = Input;
    const nav = useNavigate()

    const publishFormRef = useRef()
    const [form] = Form.useForm()

    //上传图片
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const [sortData, setSortData] = useState([]);
    const [articleContent, setContent] = useState('')

    const [draft, setDraft] = useState({})
    const [draftOpen, setDraftOpen] = useState(false)
    const {userAllInfo} = useSelector(state => state.persistedReducer.user)

    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('确认存为草稿吗？');
    const saveDraft = () => {
        if (articleContent) {
            form.validateFields().then((values) => {
                // console.log(values)
                setOpen(true);
                setDraftOpen(false)
                setDraft({...values, articleContent})
            })
        } else {
            setDraftOpen(false)
            message.info('请先编写正文')
        }
    }
    //保存草稿
    const saveDraftOk = async () => {
        console.log(draft)
        setModalText('即将存为草稿！');
        setConfirmLoading(true);
        setTimeout(async () => {
            const result = await reqInsertDraft({
                nickname: userAllInfo.nickname,
                user_id: userAllInfo.id,
                draft: {...draft, cover: draft.cover[0]}
            })
            if (result.status === 0) {
                setOpen(false);
                setConfirmLoading(false);
                nav('/my-draft')
                message.success('存为草稿成功！')
            } else {
                setOpen(false)
                setConfirmLoading(false);
                message.error('存为草稿失败，请注意标题不能重复!')
            }
        }, 1000);
    };
    const saveDraftCancel = () => {
        setOpen(false);
        setConfirmLoading(false)
    };

    useEffect(() => {
        const getSortData = async () => {
            const result = await reqGetArticleSort()
            setSortData(result.data)
        }
        getSortData()
    }, [])


    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8,}}>
                文章封面
            </div>
        </div>
    );
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };


    //确认并发布按钮
    const publish = async (articleInfo) => {
        try {
            if (articleContent) {
                const article = {...articleInfo, articleContent, cover: articleInfo.cover[0]}
                const result = await reqPublishArticle({user_id: userAllInfo.id, article})
                if (result.status === 0) {
                    message.success('发布文章成功!')
                    // console.log(article)
                    nav('/')
                } else {
                    message.error('发布失败,可能标题名出现重复！')
                }
            } else {
                setDraftOpen(false)
                message.info('请先编写正文')
            }
        } catch (err) {
            message.error(err)
        }
    }

    const handleChangeValue = (e) => {
        setContent(e)
    }
    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/writeArticle/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            const error = new Error("Some error");
            onError(err);
        }
    }

    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }


    //popover里的内容
    const content = (
        <div className={classes.PublishContainer}>
            <h2>发布文章</h2>
            <Divider/>
            <>
                <Form
                    form={form}
                    ref={publishFormRef}
                    labelCol={{span: 5}}
                    wrapperCol={{span: 16}}
                    layout="horizontal"
                    onFinish={publish}
                >
                    <Form.Item name="title" rules={[
                        {
                            required: true,
                            message: '请填写文章标题',
                        },
                    ]} label="标题">
                        <Input placeholder="输入文章标题"/>
                    </Form.Item>
                    <Form.Item name="sort" rules={[
                        {
                            required: true,
                            message: '请选择分类',
                        },
                    ]} label="分类">
                        <Select placeholder="选择文章分类"
                                options={sortData.map(item => ({value: item.sort, label: item.sort}))}/>
                    </Form.Item>
                    <Form.Item name="cover" rules={[
                        {
                            required: true,
                            message: '请选择封面',
                        },
                    ]}
                               label="选择封面"
                               getValueFromEvent={normFile}
                               valuePropName="fileList">
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            beforeUpload={beforeUpload}
                            customRequest={customRequest}
                            onChange={handleChange}

                        >
                            {imageUrl ? (
                                <img
                                    src={imageUrl}
                                    alt="avatar"
                                    style={{
                                        width: '100%',
                                    }}
                                />
                            ) : (
                                uploadButton
                            )}
                        </Upload>
                    </Form.Item>
                    <Form.Item name="introduce" rules={[
                        {
                            required: true,
                            message: '请编写摘要',
                        },
                        {
                            min: 50,
                            message: '摘要至少输入 50 个字',
                        },
                    ]} label="编辑摘要">
                        <TextArea
                            showCount
                            maxLength={100}
                            style={{
                                height: 120,
                                resize: 'none',
                            }}
                            placeholder="必填"
                        />
                    </Form.Item>

                    <Form.Item>
                        <div style={{position: "absolute", right: -100}}>
                            <Space>
                                <Button onClick={() => setDraftOpen(false)}>取消</Button>
                                <Button onClick={() => saveDraft()}>存为草稿</Button>
                                <Button type="primary" htmlType="submit">确认并发布</Button>
                            </Space>
                        </div>
                    </Form.Item>
                </Form>
            </>
        </div>
    );

    return (
        <div className={classes.WriteArticle}>
            <div className={classes.Header}>
                <div className={classes.Content}>
                    <div className={classes.Info}>
                        <Image width={35} src={icon}></Image>
                        <div>
                            <Button onClick={() => nav('/')}>返回首页</Button>
                            <Popover open={draftOpen}
                                     placement="topRight" content={content} trigger="click">
                                <Button type="primary" onClick={() => setDraftOpen(true)}>发布</Button>
                            </Popover>
                            <Image width={35} src={icon}></Image>
                        </div>
                    </div>
                </div>
            </div>
            <ReactQuill
                theme="snow"
                className={classes.ReactQuill}
                placeholder="请输入正文"
                formats={formats}
                preserveWhitespace
                // defaultValue=""
                // readOnly
                modules={modules}
                // ref={editorRef}
                // value={value}
                onChange={handleChangeValue}
                onChangeSelection={range => {
                    // console.log("onChangeSelection--->", range);
                }}
                onFocus={range => {
                    // console.log("onFocus--->", range);
                }}
                onBlur={previousRange => {
                    // console.log("onBlur--->", previousRange);
                }}
            />
            <Modal
                style={{zIndex: 1099}}
                title="存为草稿"
                open={open}
                onOk={saveDraftOk}
                confirmLoading={confirmLoading}
                onCancel={saveDraftCancel}
                okText="确认"
                cancelText="取消"
            >
                <p>{modalText}</p>
            </Modal>
        </div>
    );
};

export default WriteArticle;